﻿using AppSocketModel;
using AppSocketService.Location;
using AppSocketService.GpsRedis;
using BCGPSCommon;
using BCGPSMongoData;
using System;
using System.Collections.Concurrent;
using System.Threading; 
using System.Collections.Generic;
using Newtonsoft.Json;
using LJD.IMS.Utility;
using AppSocketService.Fence;
using AppSocketControl.GpsData.DataDispatch;
using AppSocketControl.Relay;

namespace AppSocketControl
{
    /// <summary>
    /// 收到GPS数据的处理
    /// </summary>
    public class GpsDataService : IGpsDataService
    {
        #region var
        /// <summary>
        /// 任务的容器
        /// </summary> 
        public int ThreadNumber = 0; 
        public Thread thread { set; get; }
        /// <summary>
        /// 空闲
        /// </summary>
        public bool IsIdel { set; get; }
        private string cMsg { set; get; }

        /// <summary>
        /// 处理数据总数
        /// </summary>
        private long cDataCount { set; get; }

        private readonly DispatchRunStatus dispatchDeviceRunStatus = new DispatchRunStatus();
        private readonly DispatchRstTypeCnt dispatchRstTypeCnt = new DispatchRstTypeCnt();
        private readonly DispatchLocation dispatchLocation = new DispatchLocation();
        private readonly DispatchLocationReal dispatchLocationReal = new DispatchLocationReal();
        private readonly DispatchYECmdReturn dispatchYE = new DispatchYECmdReturn();
        private readonly DispatchSendTimeSpanCmdReturn dispatchTimeSpan = new DispatchSendTimeSpanCmdReturn();
        private readonly DispatchSendTimeSpanRealCmdReturn dispatchTimeSpanReal = new DispatchSendTimeSpanRealCmdReturn();
        private readonly DispatchSleepTimeCmdReturn dispatchSleepTimeCmdReturn = new DispatchSleepTimeCmdReturn();
        private readonly DispatchSendTimesCmdReturn dispatchSendTimesCmdReturn = new DispatchSendTimesCmdReturn();
        private readonly DispatchSleepTimeOnErrCmdReturn dispatchSleepTimeOnErrCmdReturn = new DispatchSleepTimeOnErrCmdReturn();
        /// <summary>
        /// 线程运行
        /// </summary>
        public bool IsThreadRun { set; get; }
        #endregion

        #region 构造
        public GpsDataService(int threadNumber)
        {
            ThreadNumber = threadNumber;
            IsThreadRun = true;
            thread = new Thread(Run);
            thread.IsBackground = true;
            thread.Start();
        }
        #endregion

        public void SetMsg(string msg)
        {
            cMsg = msg;
            IsIdel = false ;
        }
        #region 数据处理
        public void Run()
        {
            Console.WriteLine("ThreadNumber: " + ThreadNumber + "  is begin "); 
            while (IsThreadRun)
            {
                if (IsIdel)
                {
                    Thread.Sleep(10);
                    continue;
                }

                if (!string.IsNullOrWhiteSpace(cMsg))
                {
                    try
                    { 
                        Dispatch(cMsg);
                        Msg.WirteLine($"  Over On ThreadNo:= {ThreadNumber}     {cMsg.Substring(cMsg.IndexOf("Offset:"))}    DoMsgCount:={cDataCount++}");
                    }
                    catch (System.Exception ex)
                    {
                        Msg.WirteLine($"Error*********************************** On ThreadNo:= {ThreadNumber}    in GpsDataService.Run()  {ex.Message}");
                    }
                }
                cMsg = string.Empty;
                IsIdel = true;
                continue; 
            }
            Console.WriteLine(thread.ManagedThreadId + "  is Over ");
        }
        #endregion

        #region  分流数据
        private void Dispatch(string msg)
        {
            if (msg[0] != '$')
                return;
            else
                msg = msg.TrimStart('$');

            var dataArr = msg.Split('$');
            if (dataArr.Length != 14 && dataArr.Length != 13)
                return;


            //数据转发 
            if( RelayDeviceDictionary.ImeiDict.TryGetValue(dataArr[5], out int companyId))
            {
                RelayDeviceDictionary.kafakaProducer.SendMsg("$"+companyId+msg);
            }

            try
            {
                var gpsFrameType = (GpsFrame)Enum.Parse(typeof(GpsFrame), dataArr[6]);
                switch (gpsFrameType)
                {
                    case GpsFrame.DEVICEINFO:
                        dispatchDeviceRunStatus.Run(dataArr);
                        break;
                    case GpsFrame.RSTTYPECNT:
                        dispatchRstTypeCnt.Run(dataArr);
                        break;
                    case GpsFrame.LOCATION:
                    case GpsFrame.LOCATIONLBS:
                        dispatchLocation.Run(dataArr);
                        break;
                    case GpsFrame.LOCATIONREAL:
                    case GpsFrame.LOCATIONLBSREAL:
                        dispatchLocationReal.Run(dataArr);
                        break;
                    case GpsFrame.CMDRETURNYE:
                        dispatchYE.Run(dataArr);
                        break;
                    case  GpsFrame.CMDRETURNSPAN:
                        dispatchTimeSpan.Run(dataArr);
                        break;
                    case GpsFrame.CMDRETURNREAL:
                        dispatchTimeSpanReal.Run(dataArr);
                        break;
                    case GpsFrame.CMDRETURNSLEEP:
                        dispatchSleepTimeCmdReturn.Run(dataArr);
                        break;
                    case GpsFrame.CMDRETURNSENDTIMES:
                        dispatchSendTimesCmdReturn.Run(dataArr);
                        break;
                    case GpsFrame.CMDRETURNSLEEPONERR:
                        dispatchSleepTimeOnErrCmdReturn.Run(dataArr);
                        break;
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        #endregion

    }
}
